# -*- coding: utf-8 -*-
# @Time    : 2024/1/23 21:48
# @Author  : micah
# @File    : 5.mysql协程并发.py
# @Software: PyCharm


import asyncio
import aiomysql

loop = asyncio.get_event_loop()


async def connection_mysql_linux():
    # 1.创建链接对象
    conn = await aiomysql.connect(host='localhost', port=3306, user='root', password='root', db='py_spider', loop=loop)
    # 2.创建游标
    cursor = await conn.cursor()
    # 3.执行sql
    await cursor.execute('select * from tx_work;')
    # 4.打印结果
    result = await cursor.fetchall()
    print(result)
    # 5.打印表结构
    print(cursor.description)
    # 关闭链接对象和游标对象
    await cursor.close()
    conn.close()


async def connection_mysql_windows():
    async with aiomysql.connect(host='localhost', port=3306, user='root', password='123456', db='py_spider') as conn:
        async with conn.cursor() as cursor:
            await cursor.execute('select * from tx_work;')
            result = await cursor.fetchall()
            print(result)


async def main():
    # 3.11版本不支持asyncio.wait()方法接收协程对象, 必须是task对象或者future对象
    task = [asyncio.create_task(connection_mysql_windows())]
    await asyncio.wait(task)


if __name__ == '__main__':
    # loop.run_until_complete(connection_mysql_linux())
    asyncio.run(main())
